<template>
  <div>
    <!-- 面包屑 -->
    <admin-breadcrumb :breadcrumb="breadcrumb" />
    <!-- 主要视图区域 -->
    <el-card>
      <el-row :gutter="0">
        <!-- 用户搜索 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 用户添加 -->
        <el-col :span="1">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格 -->
      <el-table id="userTable" :data="userList" border stripe style="width: 100% min-width: 1250px;">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="phone" label="电话" width="200" />
        <el-table-column prop="email" label="邮箱" width="230" />
        <el-table-column prop="role" label="角色" width="170" />
        <el-table-column label="状态" width="240">
          <template v-slot="scope">
            <el-switch v-model="scope.row.enabled" active-color="#13ce66" active-text="使上线" inactive-text="使下线" @change="userStateChanged(scope.row)" />
          </template>
        </el-table-column>
        <!-- 对用户的可执行操作 -->
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- 修改用户 -->
            <el-tooltip effect="dark" content="修改用户信息" placement="top" :open-delay="500" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row)" />
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :open-delay="500" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="small" @click="showAllotDialog(scope.row)" />
            </el-tooltip>
            <!-- 删除用户 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :open-delay="500" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="small" @click="remove(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页区域 -->
    <div class="page">
      <el-pagination @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" background layout="total, prev, pager, next, jumper" :total="count"></el-pagination>
    </div>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="addDialogClosed" :close-on-click-modal="false">
      <!-- 添加用户的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户信息的对话框 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%" :close-on-click-modal="false" @close="editDialogClosed">
      <!-- 修改用户信息的表单 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="allotRoleDialogVisible" :close-on-click-modal="false" width="50%" @close="allotRoleDialogClosed">
      <div class="allot-role">
        <p>当前用户：{{ currentUserInfo.username }}</p>
        <p>当前角色：{{ currentUserInfo.role }}</p>
        <p>
          分配角色：
          <!-- select选择器 -->
          <el-select v-model="newRoleId" placeholder="请选择">
            <el-option v-for="item in roleList" :key="item.id" :label="item.nameZh" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  metaInfo: {
    title: "后台管理-用户管理",
  },
  data() {
    // 自定义邮箱号验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱格式"));
    };
    // 自定义手机号验证规则
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regPhone.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 面包屑显示
      breadcrumb: ["用户管理", "用户列表"],

      // 获取用户列表的请求参数对象
      queryInfo: {
        // 查询的参数，可为空
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页的条目数
        pageSize: 10,
      },

      // 添加用户的对话框
      addDialogVisible: false,
      // 添加用户的表单
      addForm: {
        username: "",
        password: "",
        phone: "",
        email: "",
      },
      // 表单验证规则
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkPhone,
            trigger: "blur",
          },
        ],
      },

      // 用户列表
      userList: [],
      // 用户总数
      count: 0,

      // 修改用户信息对话框
      editDialogVisible: false,
      // 修改用户的表单
      editForm: {
        id: 0,
        username: "",
        email: "",
        phone: "",
      },
      // 表单验证规则
      editFormRules: {
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            validator: checkPhone,
            trigger: "blur",
          },
        ],
      },

      // 分配角色的对话框
      allotRoleDialogVisible: false,
      // 角色列表
      roleList: [],
      // 当前用户的信息
      currentUserInfo: {
        username: "",
        roleName: "",
      },
      // 选中的角色的id
      newRoleId: "",
    };
  },
  created() {
    this.getUserList();
  },
  updated() {},
  methods: {
    // 获取一页用户
    async getUserList() {
      // 请求一页数据
      const { data: res } = await this.$http.get("admin/user", {
        params: {
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
        },
      });
      if (res.code !== 200) return this.$message.error("获取用户列表出错");
      const loading = this.$loading({
        target: "#userTable",
        lock: true,
      });
      this.userList = res.data.userList;
      this.count = res.data.count;
      loading.close();
    },

    // 监听添加用户的表单关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUser() {
      // 表单验证是否通过
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("添加用户参数错误");
        // 发起添加用户的请求
        const { data: res } = await this.$http.post("admin/user", this.addForm);
        if (res.code !== 201)
          return this.$message.error("服务器错误，添加用户失败");
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },

    // 改变用户状态
    async userStateChanged(userInfo) {
      // 发起更新用户状态的请求
      const { data: res } = await this.$http.put(
        "admin/user/status/" + this.queryInfo.pageNum,
        userInfo
      );
      if (res.code !== 200) {
        userInfo.enabled = !userInfo.enabled;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功");
    },

    // 显示修改用户的对话框
    showEditDialog(row) {
      this.editForm.id = row.id;
      this.editForm.username = row.username;
      this.editForm.email = row.email;
      this.editForm.phone = row.phone;
      this.editDialogVisible = true;
    },
    // 修改用户信息
    edit() {
      // 验证表单
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("填写信息有误，请修改后再提交");

        // 发起修改用户数据的请求
        const { data: res } = await this.$http.put(
          "admin/user/" + this.queryInfo.pageNum,
          {
            id: this.editForm.id,
            email: this.editForm.email,
            phone: this.editForm.phone,
          }
        );
        if (res.code !== 200) {
          return this.$message.error("服务器错误，更新用户信息失败");
        }
        this.editDialogVisible = false;
        this.$message.success("更新用户信息成功");
        this.getUserList();
      });
    },
    // 关闭修改用户对话框的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 删除用户
    async remove(user) {
      const confirmResult = await this.$confirm(
        `是否删除用户[ ${user.username} ]`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info(`已取消删除用户[ ${user.username} ]`);
      }
      const { data: res } = await this.$http.delete("admin/user", {
        params: { id: user.id },
      });
      if (res.code !== 200) {
        return this.$message.error("服务器错误，删除用户失败");
      }
      this.getUserList();
    },

    // 显示分配角色的对话框
    async showAllotDialog(currentUserInfo) {
      this.allotRoleDialogVisible = true;
      this.currentUserInfo = currentUserInfo;
      // 请求角色列表
      const { data: res } = await this.$http.get("admin/role");
      if (res.code !== 200) {
        return this.$message.erro("服务器错误，分配角色列表失败");
      }
      this.roleList = res.data;
    },
    // 分配用户角色
    async allotRole() {
      if (!this.newRoleId) return this.$message.error("请选择一个角色");
      const { data: res } = await this.$http.put(
        `admin/user/allotRole/${this.currentUserInfo.id}/${this.queryInfo.pageNum}/${this.newRoleId}`
      );
      if (res.code !== 200)
        return this.$message.error("服务器错误，分配角色失败");
      this.$message.success("分配角色成功");
      this.getUserList();
      this.allotRoleDialogVisible = false;
    },
    // 监听分配角色对话框的关闭
    allotRoleDialogClosed() {
      this.currentUserInfo = {};
      this.newRoleId = "";
    },

    // 监听pagenum改变的事件，重新发起请求
    handleCurrentChange(currentPage) {
      this.queryInfo.pageNum = currentPage;
      this.getUserList();
    },
  },
};
</script>

<style lang="less" scoped>
.allot-role {
  p {
    margin: 20px 0 0 0;
    line-height: 1rem;
    font-weight: 800;
  }
}
</style>